package cn.c4ad.voa;

import java.util.ArrayList;
import java.util.HashSet;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class StatisticFragment extends Fragment {
	private static final int DAY_COUNT = 7;
	private static final float BAR_UP_WEIGHT_MIN = 0.25f;
	private static final float BAR_DOWN_WEIGHT_MIN = 0.05f;

	private int[] mSpecialPlayCountArray = new int[DAY_COUNT];
	private int[] mSpecialPlayArticalCountArray = new int[DAY_COUNT];

	private int[] mStandardPlayCountArray = new int[DAY_COUNT];
	private int[] mStandardPlayArticalCountArray = new int[DAY_COUNT];

	private View mRootView;
	private ContentResolver mContentResolver;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mRootView = inflater.inflate(R.layout.statistic_fragment, container,
				false);

		LinearLayout group = (LinearLayout) mRootView
				.findViewById(R.id.play_count_container);
		for (int i = 0; i < DAY_COUNT; i++) {
			View item = inflater.inflate(R.layout.statistic_bar_item, group,
					false);
			group.addView(item);
		}

		group = (LinearLayout) mRootView
				.findViewById(R.id.play_artical_count_container);
		for (int i = 0; i < DAY_COUNT; i++) {
			View item = inflater.inflate(R.layout.statistic_bar_item, group,
					false);
			group.addView(item);
		}

		group = (LinearLayout) mRootView
				.findViewById(R.id.standard_play_count_container);
		for (int i = 0; i < DAY_COUNT; i++) {
			View item = inflater.inflate(R.layout.statistic_bar_item, group,
					false);
			group.addView(item);
		}

		group = (LinearLayout) mRootView
				.findViewById(R.id.standard_play_artical_count_container);
		for (int i = 0; i < DAY_COUNT; i++) {
			View item = inflater.inflate(R.layout.statistic_bar_item, group,
					false);
			group.addView(item);
		}

		refreshUi();

		refreshActionBar();

		mContentResolver = getActivity().getContentResolver();

		return mRootView;
	}

	@Override
	public void onResume() {
		super.onResume();

		AsyncTask<Integer, Integer, Integer> task = new AsyncTask<Integer, Integer, Integer>() {
			private int[] specialPlayCountArray;
			private int[] specialPlayArticalCountArray;

			private int[] standardPlayCountArray;
			private int[] standardPlayArticalCountArray;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();

				specialPlayCountArray = new int[DAY_COUNT];
				specialPlayArticalCountArray = new int[DAY_COUNT];

				standardPlayCountArray = new int[DAY_COUNT];
				standardPlayArticalCountArray = new int[DAY_COUNT];
			}

			@Override
			protected Integer doInBackground(Integer... arg0) {
				int oneDay = 24 * 60 * 60 * 1000;
				long curTime = System.currentTimeMillis();
				long lastTime = curTime - 7 * oneDay;

				ArrayList<HashSet<Long>> specialArticalCount = new ArrayList<HashSet<Long>>();
				for (int i = 0; i < DAY_COUNT; i++) {
					specialArticalCount.add(new HashSet<Long>());
				}

				ArrayList<HashSet<Long>> standardArticalCount = new ArrayList<HashSet<Long>>();
				for (int i = 0; i < DAY_COUNT; i++) {
					standardArticalCount.add(new HashSet<Long>());
				}

				Cursor cursor = mContentResolver.query(
						VoaContentProvider.PLAY_CONTENT_URI, null,
						VoaContentProvider.PLAY_TIME + ">?",
						new String[] { String.valueOf(lastTime) }, null);
				if (cursor != null) {
					while (cursor.moveToNext()) {
						Long articalId = cursor.getLong(cursor
								.getColumnIndex(VoaContentProvider.ARTICAL_ID));
						long time = cursor.getLong(cursor
								.getColumnIndex(VoaContentProvider.PLAY_TIME));
						int index = (int) (((time - lastTime) / oneDay) % DAY_COUNT);
						int articalType = getArticalType(articalId);
						if (articalType == VoaContentProvider.TYPE_SPECIAL) {
							specialPlayCountArray[index] = specialPlayCountArray[index] + 1;
							specialArticalCount.get(index).add(articalId);
						} else if (articalType == VoaContentProvider.TYPE_STANDARD) {
							standardPlayCountArray[index] = standardPlayCountArray[index] + 1;
							standardArticalCount.get(index).add(articalId);
						}
					}
					cursor.close();
				}

				for (int i = 0; i < DAY_COUNT; i++) {
					specialPlayArticalCountArray[i] = specialArticalCount
							.get(i).size();
				}

				for (int i = 0; i < DAY_COUNT; i++) {
					standardPlayArticalCountArray[i] = standardArticalCount
							.get(i).size();
				}

				return 0;
			}

			@Override
			protected void onPostExecute(Integer result) {
				super.onPostExecute(result);
				mSpecialPlayCountArray = specialPlayCountArray;
				mSpecialPlayArticalCountArray = specialPlayArticalCountArray;

				mStandardPlayCountArray = standardPlayCountArray;
				mStandardPlayArticalCountArray = standardPlayArticalCountArray;
				refreshUi();
			}
		};
		task.execute(0);
	}

	private void refreshActionBar() {
		View actionBarView = getActivity().getActionBar().getCustomView();
		TextView title = (TextView) actionBarView.findViewById(R.id.title);
		title.setText(R.string.ic_statistic);

		TextView right = (TextView) actionBarView
				.findViewById(R.id.rightButton);
		right.setText(null);
		right.setVisibility(View.GONE);
	}

	private int updateStatisticBar(int[] countArray, ViewGroup container) {
		int sum = 0;
		int max = 0;
		for (int count : countArray) {
			sum += count;
			max = Math.max(max, count);
		}

		for (int i = 0; i < countArray.length && i < container.getChildCount(); i++) {
			float downWeight = BAR_DOWN_WEIGHT_MIN;
			if (max > 0) {
				downWeight += (1 - BAR_UP_WEIGHT_MIN - BAR_DOWN_WEIGHT_MIN)
						* countArray[i] / max;
			}
			float upWeight = 1 - downWeight;
			View item = container.getChildAt(i);
			TextView up = (TextView) item
					.findViewById(R.id.statistic_bar_count);
			up.setText(String.valueOf(countArray[i]));
			LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) up
					.getLayoutParams();
			layout.weight = upWeight;
			up.requestLayout();

			View down = item.findViewById(R.id.statistic_bar_icon);
			layout = (LinearLayout.LayoutParams) down.getLayoutParams();
			layout.weight = downWeight;
			down.requestLayout();
		}

		return sum;
	}

	private void refreshUi() {
		LinearLayout group = (LinearLayout) mRootView
				.findViewById(R.id.play_count_container);
		int sum = updateStatisticBar(mSpecialPlayCountArray, group);
		TextView title = (TextView) mRootView
				.findViewById(R.id.play_count_title);
		title.setText(getResources().getString(R.string.play_count)
				+ String.valueOf(sum));

		group = (LinearLayout) mRootView
				.findViewById(R.id.play_artical_count_container);
		sum = updateStatisticBar(mSpecialPlayArticalCountArray, group);
		title = (TextView) mRootView
				.findViewById(R.id.play_artical_count_title);
		title.setText(getResources().getString(R.string.play_artical_count)
				+ String.valueOf(sum));

		group = (LinearLayout) mRootView
				.findViewById(R.id.standard_play_count_container);
		sum = updateStatisticBar(mStandardPlayCountArray, group);
		title = (TextView) mRootView
				.findViewById(R.id.standard_play_count_title);
		title.setText(getResources().getString(R.string.play_count)
				+ String.valueOf(sum));

		group = (LinearLayout) mRootView
				.findViewById(R.id.standard_play_artical_count_container);
		sum = updateStatisticBar(mStandardPlayArticalCountArray, group);
		title = (TextView) mRootView
				.findViewById(R.id.standard_play_artical_count_title);
		title.setText(getResources().getString(R.string.play_artical_count)
				+ String.valueOf(sum));
	}

	private int getArticalType(long articalId) {
		int articalType = 0;
		Uri uri = ContentUris.withAppendedId(
				VoaContentProvider.ARTICAL_CONTENT_URI, articalId);
		Cursor cursor = mContentResolver.query(uri, null, null, null, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				articalType = cursor.getInt(cursor
						.getColumnIndex(VoaContentProvider.TYPE));
			}
			cursor.close();
		}
		return articalType;
	}
}
